<template>
    <div>
        <el-select v-model="selectedTable" placeholder="选择一个表" @change="fetchData">
            <el-option v-for="table in tables" :key="table" :label="table" :value="table"/>
        </el-select>
        <el-card style="margin-top: 20px">
            <el-table :border="true" :stripe="true" :data="tableData" v-if="selectedTable">
                <el-table-column v-for="column in columns" :prop="column" :label="column" :key="column">
                    <template #default="scope">
                        <template v-if="isEditing(scope.row)">
                            <el-input v-model="editCache[scope.row.id][column]"/>
                        </template>
                        <template v-else>
                            {{ scope.row[column] }}
                        </template>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="350">
                    <template v-slot="scope" style="display: flex;flex-direction: row;justify-content: center">
                        <template v-if="isEditing(scope.row)">
                            <el-button @click="saveData(scope.row)" size="default" type="primary">保存</el-button>
                            <el-button @click="cancelEdit(scope.row)" size="default" type="danger">取消</el-button>
                        </template>
                        <template v-else>
                            <el-button @click="editData(scope.row)" size="default">编辑</el-button>
                            <el-button @click="deleteData(scope.row)" size="default" type="danger">删除</el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <el-button style="margin-top: 30px" @click="createData" type="primary">新增</el-button>
        </el-card>
        <el-dialog v-model="isDialogVisible" title="新增数据">
            <el-form :model="newData">
                <el-form-item v-for="column in columns" :label="column" :key="column">
                    <el-input v-model="newData[column]"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="isDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveNewData">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>


<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {
    createTableData,
    deleteTableData,
    getTableData,
    getTables,
    updateTableData
} from "@/service/teacher/teacher.service";
import {ElMessage} from "element-plus";

const selectedTable = ref('');
const tables = ref([]);
const tableData = ref([]);
const columns = ref([]);
const editCache = ref<Record<string, any>>({});
const isDialogVisible = ref(false);
const newData = ref<Record<string, any>>({});

onMounted(() => {
    getTables((data: any) => {
        for (const table of data.tableList) {
            tables.value.push(table);
        }
    });
});

const fetchData = async () => {
    if (!selectedTable.value) return;
    getTableData(selectedTable.value, toCamelCase(selectedTable.value), (data: any) => {
        tableData.value = data.table;
        columns.value = Object.keys(data.table[0] || {});
        editCache.value = {}; // 重置编辑缓存
    });
};

const createData = () => {
    // 打开一个对话框，输入新数据并提交
    newData.value = {}; // 清空新数据对象
    isDialogVisible.value = true; // 显示对话框
};

const editData = (row: any) => {
    if (!editCache.value[row.id]) {
        editCache.value[row.id] = {...row};
    }
};

const isEditing = (row: any) => {
    return !!editCache.value[row.id];
};

const saveData = (row: any) => {
    const updatedRow = editCache.value[row.id];
    const tableName = selectedTable.value;
    const entityClass = toCamelCase(tableName);
    updateTableData(tableName, entityClass, convertProxyToFormData(updatedRow), (data) => {
        ElMessage({
            message: "更新成功",
            type: "success",
            duration: 2000
        });
        fetchData(); // 更新成功后刷新表格数据
        delete editCache.value[row.id];
    });
};

const cancelEdit = (row: any) => {
    delete editCache.value[row.id];
};

const deleteData = (row: any) => {
    // 发送删除请求到服务器
    const updatedRow = row;
    const tableName = selectedTable.value;
    const entityClass = toCamelCase(tableName);
    deleteTableData(tableName, entityClass, convertProxyToFormData(updatedRow), (data) => {
        ElMessage({
            message: "删除成功",
            type: "success",
            duration: 2000
        });
        fetchData(); // 更新成功后刷新表格数据
        delete editCache.value[row.id];
    });
};

const saveNewData = () => {
    const tableName = selectedTable.value;
    const entityClass = toCamelCase(tableName);
    createTableData(tableName, entityClass, convertProxyToFormData(newData.value), (data) => {
        ElMessage({
            message: "新增成功",
            type: "success",
            duration: 2000
        });
        fetchData(); // 新增成功后刷新表格数据
        isDialogVisible.value = false; // 关闭对话框
    });
};


/**
 * 转驼峰式
 * @param str
 */
function toCamelCase(str: string) {
    return str
        .split('_') // 以 "_" 分隔字符串
        .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) // 每个单词首字母大写
        .join(''); // 合并成一个字符串
}

/**
 * 获取表单数据
 * @param proxyObject
 */
function convertProxyToFormData(proxyObject) {
    const formData = new reactive({})
    
    // 获取 Proxy 对象的所有属性名
    const keys = Object.keys(proxyObject);
    
    // 遍历属性名，将其添加到 FormData 中
    keys.forEach(key => {
        // 获取代理对象中键对应的值
        formData[key] = proxyObject[key]; // 设置formData中的键值对，键是变量key
    });
    
    return formData;
}
</script>

<style>
/* 添加你的样式 */
</style>
